<template>
  <CustomEcharts :id="props.id" height="100%" width="100%" :full-options="echartsOptions" :loading="false">
  </CustomEcharts>
</template>

<script setup>
import { onMounted, reactive, defineProps, watch } from "vue";
import CustomEcharts from './customEcharts.vue';
import * as echarts from 'echarts';

const props = defineProps({
  echartsData: {
    type: Array,
    default: () => []
  },
  id: String,
  deptName: {
    type: String,
    default: ''
  }
});

const echartsOptions = reactive({
  options: {}
});

const createOption = () => {
  if (!props.echartsData || !props.echartsData.length) return {};

  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'];
  
  const data = props.echartsData.map((item, index) => ({
    value: item.value,
    name: item.name,
    itemStyle: {
      color: colors[index % colors.length]
    }
  }));

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      top: '0%',
      left: 'center'
    },
    series: [
      {
        name: '项目类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {d}%'
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 20
        },
        data: data
      }
    ]
  };
};

// 监听数据变化
watch(() => props.echartsData, (newVal) => {
  if (newVal) {
    echartsOptions.options = createOption();
  }
}, { 
  deep: true, 
  immediate: true  // 确保首次加载时执行
});

onMounted(() => {
  echartsOptions.options = createOption();
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
}
</style>